package com.txzt.gaea.common.base.service.impl;

import com.txzt.gaea.common.base.service.BaseService;
import com.txzt.gaea.common.util.StringUtil;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * Created by Leo on 18/6/6.
 */
@Service
public class BaseServiceImpl<T> implements BaseService<T> {

    @Autowired
    protected SQLManager sqlManager;

    @Override
    public T selectById(Integer id) {
        //Class<T> tClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        Class<T> tClass = getTClass();
        return sqlManager.single(tClass, id);
    }

    @Override
    public T selectById(Long id) {
        //Class<T> tClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        Class<T> tClass = getTClass();
        return sqlManager.single(tClass, id);
    }

    public T selectOne(T t) {
        return sqlManager.templateOne(t);
    }

    @Override
    public List<T> query() {
        return sqlManager.query(getTClass()).select();
    }

    @Override
    public PageQuery<T> pageQuery(PageQuery<T> pageQuery) {

        String className = getTClass().getSimpleName();
        if (StringUtil.isNotEmpty(className)) {
            //className = className.toLowerCase();//Linux 区分大小写
            className = className.substring(0, 1).toLowerCase() + className.substring(1);
        }
        return sqlManager.pageQuery(className + ".queryByCondition", getTClass(), pageQuery);
    }

    @Override
    public PageQuery<T> pageQuery(String sqlId, PageQuery<T> pageQuery) {
        return sqlManager.pageQuery(sqlId, getTClass(), pageQuery);
    }

    @Override
    public int save(T t) {
        return sqlManager.insertTemplate(t, true);
    }

    @Override
    public int delete(T t) {
        return sqlManager.deleteObject(t);
    }

    @Override
    public int deleteById(Integer id) {
        Class<T> tClass = getTClass();
        return sqlManager.deleteById(tClass, id);
    }

    @Override
    public int deleteById(Long id) {
        Class<T> tClass = getTClass();
        return sqlManager.deleteById(tClass, id);
    }

    @Override
    public int updateById(T t) {
        return sqlManager.updateTemplateById(t);
    }

    @Override
    public int insertTemplate(T t) {
        return sqlManager.insertTemplate(t);
    }

    @Override
    public int[] insertBatch(Class<T> t, List<T> list){
        return sqlManager.insertBatch(t, list);
    }

    /**
     * 获取泛型的Classs实例
     * @return
     */
    protected Class<T> getTClass() {
        return (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

}
